const express = require('express');
const { body } = require('express-validator');
const caregiverController = require('../controllers/caregiverController');
const { protect, restrictTo, optionalAuth } = require('../middleware/auth');
const rateLimit = require('express-rate-limit');

const router = express.Router();

// 限制护理员操作请求的频率
const caregiverLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 100, // 限制每个IP 15分钟内最多100次请求
  message: {
    status: 'error',
    message: '请求过于频繁，请稍后再试'
  },
  standardHeaders: true,
  legacyHeaders: false
});

// 限制档案创建请求的频率
const createProfileLimiter = rateLimit({
  windowMs: 24 * 60 * 60 * 1000, // 24小时
  max: 3, // 限制每个IP 24小时内最多3次档案创建请求
  message: {
    status: 'error',
    message: '档案创建过于频繁，请24小时后再试'
  },
  standardHeaders: true,
  legacyHeaders: false
});

// 验证规则
const createProfileValidation = [
  body('experience')
    .isInt({ min: 0, max: 50 })
    .withMessage('经验年限必须是0-50之间的整数'),
  
  body('skills')
    .isArray({ min: 1 })
    .withMessage('至少需要选择一项技能')
    .custom((value) => {
      const validSkills = [
        'dog_care', 'cat_care', 'bird_care', 'fish_care', 'rabbit_care',
        'reptile_care', 'small_animal_care', 'medication_administration',
        'grooming', 'training', 'walking', 'feeding', 'overnight_care',
        'emergency_care', 'senior_pet_care', 'puppy_care', 'kitten_care'
      ];
      if (!value.every(skill => validSkills.includes(skill))) {
        throw new Error('包含无效的技能选项');
      }
      return true;
    }),
  
  body('certificates')
    .optional()
    .isArray()
    .withMessage('证书信息必须是数组'),
  
  body('certificates.*.name')
    .optional()
    .isLength({ min: 1, max: 100 })
    .withMessage('证书名称长度必须在1-100个字符之间'),
  
  body('certificates.*.issuer')
    .optional()
    .isLength({ min: 1, max: 100 })
    .withMessage('颁发机构名称长度必须在1-100个字符之间'),
  
  body('certificates.*.issueDate')
    .optional()
    .isISO8601()
    .withMessage('颁发日期格式无效'),
  
  body('certificates.*.expiryDate')
    .optional()
    .isISO8601()
    .withMessage('过期日期格式无效'),
  
  body('serviceArea.address')
    .isLength({ min: 1, max: 200 })
    .withMessage('服务地址长度必须在1-200个字符之间'),
  
  body('serviceArea.city')
    .isLength({ min: 1, max: 100 })
    .withMessage('城市名称长度必须在1-100个字符之间'),
  
  body('serviceArea.coordinates')
    .isArray({ min: 2, max: 2 })
    .withMessage('坐标必须是包含经度和纬度的数组'),
  
  body('serviceArea.radius')
    .isFloat({ min: 1, max: 50 })
    .withMessage('服务半径必须在1-50公里之间'),
  
  body('availability.schedule')
    .isObject()
    .withMessage('日程安排必须是对象'),
  
  body('availability.maxPetsPerDay')
    .isInt({ min: 1, max: 20 })
    .withMessage('每日最大宠物数量必须在1-20之间'),
  
  body('availability.acceptsOvernight')
    .isBoolean()
    .withMessage('是否接受过夜护理必须是布尔值'),
  
  body('availability.acceptsEmergency')
    .isBoolean()
    .withMessage('是否接受紧急护理必须是布尔值'),
  
  body('pricing.baseRate')
    .isFloat({ min: 10, max: 1000 })
    .withMessage('基础费率必须在10-1000之间'),
  
  body('pricing.currency')
    .isIn(['CNY', 'USD', 'EUR'])
    .withMessage('货币类型必须是 CNY、USD 或 EUR'),
  
  body('pricing.overnightRate')
    .optional()
    .isFloat({ min: 0 })
    .withMessage('过夜费率必须是非负数'),
  
  body('pricing.emergencyRate')
    .optional()
    .isFloat({ min: 0 })
    .withMessage('紧急护理费率必须是非负数'),
  
  body('insurance.provider')
    .optional()
    .isLength({ min: 1, max: 100 })
    .withMessage('保险公司名称长度必须在1-100个字符之间'),
  
  body('insurance.policyNumber')
    .optional()
    .isLength({ min: 1, max: 50 })
    .withMessage('保单号长度必须在1-50个字符之间'),
  
  body('emergencyContact.name')
    .isLength({ min: 1, max: 100 })
    .withMessage('紧急联系人姓名长度必须在1-100个字符之间'),
  
  body('emergencyContact.phone')
    .isMobilePhone('zh-CN')
    .withMessage('请提供有效的手机号码'),
  
  body('emergencyContact.relationship')
    .isLength({ min: 1, max: 50 })
    .withMessage('关系描述长度必须在1-50个字符之间')
];

const updateProfileValidation = [
  body('experience')
    .optional()
    .isInt({ min: 0, max: 50 })
    .withMessage('经验年限必须是0-50之间的整数'),
  
  body('skills')
    .optional()
    .isArray({ min: 1 })
    .withMessage('至少需要选择一项技能'),
  
  body('serviceArea.radius')
    .optional()
    .isFloat({ min: 1, max: 50 })
    .withMessage('服务半径必须在1-50公里之间'),
  
  body('availability.maxPetsPerDay')
    .optional()
    .isInt({ min: 1, max: 20 })
    .withMessage('每日最大宠物数量必须在1-20之间'),
  
  body('pricing.baseRate')
    .optional()
    .isFloat({ min: 10, max: 1000 })
    .withMessage('基础费率必须在10-1000之间')
];

const availabilityValidation = [
  body('availability.schedule')
    .optional()
    .isObject()
    .withMessage('日程安排必须是对象'),
  
  body('availability.maxPetsPerDay')
    .optional()
    .isInt({ min: 1, max: 20 })
    .withMessage('每日最大宠物数量必须在1-20之间'),
  
  body('availability.acceptsOvernight')
    .optional()
    .isBoolean()
    .withMessage('是否接受过夜护理必须是布尔值'),
  
  body('availability.acceptsEmergency')
    .optional()
    .isBoolean()
    .withMessage('是否接受紧急护理必须是布尔值')
];

const unavailableDateValidation = [
  body('startDate')
    .isISO8601()
    .withMessage('开始日期格式无效')
    .custom((value) => {
      const startDate = new Date(value);
      const now = new Date();
      if (startDate < now) {
        throw new Error('开始日期不能是过去时间');
      }
      return true;
    }),
  
  body('endDate')
    .isISO8601()
    .withMessage('结束日期格式无效')
    .custom((value, { req }) => {
      const endDate = new Date(value);
      const startDate = new Date(req.body.startDate);
      if (endDate <= startDate) {
        throw new Error('结束日期必须晚于开始日期');
      }
      return true;
    }),
  
  body('reason')
    .optional()
    .isLength({ max: 200 })
    .withMessage('原因说明不能超过200个字符')
];

const pricingValidation = [
  body('pricing.baseRate')
    .optional()
    .isFloat({ min: 10, max: 1000 })
    .withMessage('基础费率必须在10-1000之间'),
  
  body('pricing.overnightRate')
    .optional()
    .isFloat({ min: 0 })
    .withMessage('过夜费率必须是非负数'),
  
  body('pricing.emergencyRate')
    .optional()
    .isFloat({ min: 0 })
    .withMessage('紧急护理费率必须是非负数'),
  
  body('pricing.additionalPetRate')
    .optional()
    .isFloat({ min: 0 })
    .withMessage('额外宠物费率必须是非负数')
];

const verificationValidation = [
  body('verified')
    .isBoolean()
    .withMessage('验证状态必须是布尔值'),
  
  body('verificationNotes')
    .optional()
    .isLength({ max: 500 })
    .withMessage('验证备注不能超过500个字符')
];

const statusValidation = [
  body('status')
    .isIn(['active', 'inactive', 'suspended'])
    .withMessage('状态必须是 active、inactive 或 suspended')
];

// 应用限流中间件到所有路由
router.use(caregiverLimiter);

// 公开路由（可选认证）

/**
 * @route   GET /api/caregivers/search
 * @desc    搜索护理员
 * @access  Public
 */
router.get('/search', optionalAuth, caregiverController.searchCaregivers);

/**
 * @route   GET /api/caregivers/:id
 * @desc    获取单个护理员信息
 * @access  Public
 */
router.get('/:id', optionalAuth, caregiverController.getCaregiver);

// 所有路由都需要认证
router.use(protect);

// 护理员个人操作

/**
 * @route   GET /api/caregivers/me/profile
 * @desc    获取当前护理员档案
 * @access  Private
 */
router.get('/me/profile', caregiverController.getMyProfile);

/**
 * @route   POST /api/caregivers/me/profile
 * @desc    创建护理员档案
 * @access  Private
 */
router.post('/me/profile', 
  createProfileLimiter,
  caregiverController.uploadCertificates,
  caregiverController.processCertificates,
  createProfileValidation,
  caregiverController.createProfile
);

/**
 * @route   PATCH /api/caregivers/me/profile
 * @desc    更新护理员档案
 * @access  Private
 */
router.patch('/me/profile',
  caregiverController.uploadCertificates,
  caregiverController.processCertificates,
  updateProfileValidation,
  caregiverController.updateProfile
);

/**
 * @route   DELETE /api/caregivers/me/profile
 * @desc    删除护理员档案
 * @access  Private
 */
router.delete('/me/profile', caregiverController.deleteProfile);

/**
 * @route   PATCH /api/caregivers/me/availability
 * @desc    更新可用性
 * @access  Private/Caregiver
 */
router.patch('/me/availability',
  restrictTo('caregiver', 'admin'),
  availabilityValidation,
  caregiverController.updateAvailability
);

/**
 * @route   POST /api/caregivers/me/unavailable
 * @desc    添加不可用日期
 * @access  Private/Caregiver
 */
router.post('/me/unavailable',
  restrictTo('caregiver', 'admin'),
  unavailableDateValidation,
  caregiverController.addUnavailableDate
);

/**
 * @route   PATCH /api/caregivers/me/pricing
 * @desc    更新定价
 * @access  Private/Caregiver
 */
router.patch('/me/pricing',
  restrictTo('caregiver', 'admin'),
  pricingValidation,
  caregiverController.updatePricing
);

/**
 * @route   GET /api/caregivers/me/earnings
 * @desc    获取收入统计
 * @access  Private/Caregiver
 */
router.get('/me/earnings',
  restrictTo('caregiver', 'admin'),
  caregiverController.getEarningsStats
);

// 管理员功能

/**
 * @route   GET /api/caregivers/stats
 * @desc    获取护理员统计信息
 * @access  Private/Admin
 */
router.get('/stats', restrictTo('admin'), caregiverController.getCaregiverStats);

/**
 * @route   GET /api/caregivers
 * @desc    获取所有护理员
 * @access  Private/Admin
 */
router.get('/', restrictTo('admin'), caregiverController.getAllCaregivers);

/**
 * @route   PATCH /api/caregivers/:id/verify
 * @desc    验证护理员
 * @access  Private/Admin
 */
router.patch('/:id/verify',
  restrictTo('admin'),
  verificationValidation,
  caregiverController.verifyCaregiver
);

/**
 * @route   PATCH /api/caregivers/:id/status
 * @desc    更新护理员状态
 * @access  Private/Admin
 */
router.patch('/:id/status',
  restrictTo('admin'),
  statusValidation,
  caregiverController.toggleCaregiverStatus
);

module.exports = router;